package com.qianduo.front.service;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;

import au.id.jericho.lib.html.Source;

import com.qianduo.front.model.City;
import com.qianduo.front.model.Daikuan;
import com.qianduo.front.model.DaikuanCondition;
import com.qianduo.front.util.Constants;

import common.util.StringUtil;

public class ReadDaikuanService extends CommonService{	
	@SuppressWarnings("finally")
	public List<Daikuan> getDaikuanList(String daikuanID,String amount,String interestRate,String month,String cityID,String companyID,String daikuanTypeID,String currentPage,String pageSize){
		List<Daikuan> retList	= null;
		InputStreamReader isr	= null;
		try{
			StringBuilder querySB	= new StringBuilder(Constants.remoteUrl);
			querySB.append("daikuanServlet?action=daikuanList");
			if(!StringUtil.isEmpty(daikuanID)){
				querySB.append("&id=").append(daikuanID);
			}
			if(!StringUtil.isEmpty(amount)){
				querySB.append("&amount=").append(amount);
			}
			if(!StringUtil.isEmpty(interestRate)){
				querySB.append("&interestRate=").append(interestRate);
			}
			if(!StringUtil.isEmpty(month)){
				querySB.append("&month=").append(month);
			}
			if(!StringUtil.isEmpty(cityID)){
				querySB.append("&cityID=").append(cityID);
			}
			if(!StringUtil.isEmpty(companyID)){
				querySB.append("&companyID=").append(companyID);
			}
			if(!StringUtil.isEmpty(daikuanTypeID)){
				querySB.append("&daikuanTypeID=").append(daikuanTypeID);
			}
			if(!StringUtil.isEmpty(currentPage)){
				querySB.append("&startPage=").append(currentPage);
			}
			if(!StringUtil.isEmpty(pageSize)){
				querySB.append("&pageSize=").append(pageSize);
			}
			HttpResponse res	= commonGet(false, null, querySB.toString(), null, null, null);
			if(HttpStatus.SC_OK == res.getStatusLine().getStatusCode()){
				isr				= new InputStreamReader(res.getEntity().getContent(),"utf-8");
				String resString= new Source(isr).toString();
				if(resString.startsWith("[")){
					JSONArray jsonArray	= JSONArray.fromObject(resString);
					if(null != jsonArray && jsonArray.size() > 0){
						retList	= new ArrayList<Daikuan>();						
						for(int i=0;i<jsonArray.size();i++){
							JSONObject obj			= jsonArray.getJSONObject(i);
							String cities			= obj.getString("cities");
							String companyName 		= obj.getString("companyName");
							String tmpCompanyID 	= obj.getString("companyID");
							String conditionsApply 	= obj.getString("conditionsApply");
							String daikuanTypeName 	= obj.getString("daikuanTypeName");
							String tmpDaikuanTypeID	= obj.getString("daikuanTypeID");
							String description 		= obj.getString("description");
							String id 				= obj.getString("id");
							String image 			= obj.getString("image");
							String isActive 		= obj.getString("isActive");
							String loansTime 		= obj.getString("loansTime");
							String materialsNeeded 	= obj.getString("materialsNeeded");							
							String maxAge	 		= obj.getString("maxAge");							
							String maxAmount 		= obj.getString("maxAmount");
							String maxBorrowingTime = obj.getString("maxBorrowingTime");
							String maxInterestRate 	= obj.getString("maxInterestRate");
							String minAge	 		= obj.getString("minAge");
							String minAmount 		= obj.getString("minAmount");
							String minBorrowingTime = obj.getString("minBorrowingTime");
							String minInterestRate 	= obj.getString("minInterestRate");
							String name 			= obj.getString("name");
							String operateTime 		= obj.getString("operateTime");
							String organization		= obj.getString("organization");
							String rateDescription	= obj.getString("rateDescription");
							String requirementsDescription	= obj.getString("requirementsDescription");
							String summary  		= obj.getString("summary");
							String wage 			= obj.getString("wage");
							String wagePunch 		= obj.getString("wagePunch");
							String workTime  		= obj.getString("workTime");

							String repaymentTypeID  = obj.getString("repaymentTypeID");
							String professions  	= obj.getString("professions");
							String estates  		= obj.getString("estates");
							String securedcars  	= obj.getString("securedcars");
							String creditHistories	= obj.getString("creditHistories");
							
							
							Daikuan dk	= new Daikuan();
							dk.setCities(cities);
							dk.setCompanyName(companyName);
							dk.setCompanyID(tmpCompanyID);
							dk.setConditionsApply(conditionsApply);
							dk.setDaikuanTypeName(daikuanTypeName);
							dk.setDaikuanTypeID(tmpDaikuanTypeID);
							dk.setDescription(description);
							dk.setId(id);
							dk.setImage(image);
							dk.setIsActive(isActive);
							dk.setLoansTime(loansTime);
							dk.setMaterialsNeeded(materialsNeeded);
							dk.setMaxAge(maxAge);
							dk.setMaxAmount(maxAmount);
							dk.setMaxBorrowingTime(maxBorrowingTime);
							dk.setMaxInterestRate(maxInterestRate);
							dk.setMinAge(minAge);
							dk.setMinAmount(minAmount);
							dk.setMinBorrowingTime(minBorrowingTime);
							dk.setMinInterestRate(minInterestRate);
							dk.setName(name);
							dk.setOperateTime(operateTime);
							dk.setOrganization(organization);
							dk.setRateDescription(rateDescription);
							dk.setRequirementsDescription(requirementsDescription);
							dk.setSummary(summary);
							dk.setWage(wage);
							dk.setWagePunch(wagePunch);
							dk.setWorkTime(workTime);
							dk.setRepaymentTypeID(repaymentTypeID);
							dk.setProfessions(professions);
							dk.setEstates(estates);
							dk.setSecuredcars(securedcars);
							dk.setCreditHistories(creditHistories);
							
							retList.add(dk);
						}
					}
				}
			}
		}catch(Exception e){
			Constants.log.error(className+" getDaikuanList",e);
		}finally{
			try {
				isr.close();
			} catch (IOException e) {
				Constants.log.error(className+" getDaikuanList isr",e);
			}
			return retList;
		}
	}
	
	@SuppressWarnings({ "finally", "unchecked" })
	public Map<String,String> getCompany(){
		Map<String,String> retMap	= null;
		InputStreamReader isr		= null;
		try{
			StringBuilder querySB	= new StringBuilder(Constants.remoteUrl);
			querySB.append("daikuanServlet?action=getCompany");
			HttpResponse res		= commonGet(false, null, querySB.toString(), null, null, null);
			if(HttpStatus.SC_OK == res.getStatusLine().getStatusCode()){
				retMap			= new HashMap<String,String>();
				isr				= new InputStreamReader(res.getEntity().getContent(),"utf-8");
				String resString= new Source(isr).toString();
				if(resString.startsWith("{")){
					JSONObject obj		= JSONObject.fromObject(resString);
					Set<String> keys	= obj.keySet();
					for(String key : keys){
						String value	= obj.getString(key);
						retMap.put(key, value);
					}
				}
			}
		}catch(Exception e){
			Constants.log.error(className+" getCompany",e);
		}finally{
			try {
				isr.close();
			} catch (IOException e) {
				Constants.log.error(className+" getCompany isr",e);
			}
			return retMap;
		}
	}
	
	@SuppressWarnings({ "finally", "unchecked" })
	public Map<String,String> getRepayment(){
		Map<String,String> retMap	= null;
		InputStreamReader isr		= null;
		try{
			StringBuilder querySB	= new StringBuilder(Constants.remoteUrl);
			querySB.append("daikuanServlet?action=getRepayment");
			HttpResponse res		= commonGet(false, null, querySB.toString(), null, null, null);
			if(HttpStatus.SC_OK == res.getStatusLine().getStatusCode()){
				retMap			= new HashMap<String,String>();
				isr				= new InputStreamReader(res.getEntity().getContent(),"utf-8");
				String resString= new Source(isr).toString();
				if(resString.startsWith("{")){
					JSONObject obj		= JSONObject.fromObject(resString);
					Set<String> keys	= obj.keySet();
					for(String key : keys){
						String value	= obj.getString(key);
						retMap.put(key, value);
					}
				}
			}
		}catch(Exception e){
			Constants.log.error(className+" getRepayment",e);
		}finally{
			try {
				isr.close();
			} catch (IOException e) {
				Constants.log.error(className+" getRepayment isr",e);
			}
			return retMap;
		}
	}
	
	@SuppressWarnings({ "finally", "unchecked" })
	public Map<String,String> getMortgage(){
		Map<String,String> retMap	= null;
		InputStreamReader isr		= null;
		try{
			StringBuilder querySB	= new StringBuilder(Constants.remoteUrl);
			querySB.append("daikuanServlet?action=getMortgage");
			HttpResponse res		= commonGet(false, null, querySB.toString(), null, null, null);
			if(HttpStatus.SC_OK == res.getStatusLine().getStatusCode()){
				retMap			= new HashMap<String,String>();
				isr				= new InputStreamReader(res.getEntity().getContent(),"utf-8");
				String resString= new Source(isr).toString();
				if(resString.startsWith("{")){
					JSONObject obj		= JSONObject.fromObject(resString);
					Set<String> keys	= obj.keySet();
					for(String key : keys){
						String value	= obj.getString(key);
						retMap.put(key, value);
					}
				}
			}
		}catch(Exception e){
			Constants.log.error(className+" getMortgage",e);
		}finally{
			try {
				isr.close();
			} catch (IOException e) {
				Constants.log.error(className+" getMortgage isr",e);
			}
			return retMap;
		}
	}
	
	@SuppressWarnings({ "finally", "unchecked" })
	public Map<String,String> getDaikuanType(){
		Map<String,String> retMap	= null;
		InputStreamReader isr		= null;
		try{
			StringBuilder querySB	= new StringBuilder(Constants.remoteUrl);
			querySB.append("daikuanServlet?action=getDaikuanType");
			HttpResponse res		= commonGet(false, null, querySB.toString(), null, null, null);
			if(HttpStatus.SC_OK == res.getStatusLine().getStatusCode()){
				retMap			= new HashMap<String,String>();
				isr				= new InputStreamReader(res.getEntity().getContent(),"utf-8");
				String resString= new Source(isr).toString();
				if(resString.startsWith("{")){
					JSONObject obj		= JSONObject.fromObject(resString);
					Set<String> keys	= obj.keySet();
					for(String key : keys){
						String value	= obj.getString(key);
						retMap.put(key, value);
					}
				}
			}
		}catch(Exception e){
			Constants.log.error(className+" getDaikuanType",e);
		}finally{
			try {
				isr.close();
			} catch (IOException e) {
				Constants.log.error(className+" getDaikuanType isr",e);
			}
			return retMap;
		}
	}
	
	@SuppressWarnings({ "finally", "unchecked" })
	public Map<String,String> getEstate(){
		Map<String,String> retMap	= null;
		InputStreamReader isr		= null;
		try{
			StringBuilder querySB	= new StringBuilder(Constants.remoteUrl);
			querySB.append("daikuanServlet?action=getEstate");
			HttpResponse res		= commonGet(false, null, querySB.toString(), null, null, null);
			if(HttpStatus.SC_OK == res.getStatusLine().getStatusCode()){
				retMap			= new HashMap<String,String>();
				isr				= new InputStreamReader(res.getEntity().getContent(),"utf-8");
				String resString= new Source(isr).toString();
				if(resString.startsWith("{")){
					JSONObject obj		= JSONObject.fromObject(resString);
					Set<String> keys	= obj.keySet();
					for(String key : keys){
						String value	= obj.getString(key);
						retMap.put(key, value);
					}
				}
			}
		}catch(Exception e){
			Constants.log.error(className+" getEstate",e);
		}finally{
			try {
				isr.close();
			} catch (IOException e) {
				Constants.log.error(className+" getEstate isr",e);
			}
			return retMap;
		}
	}
	
	@SuppressWarnings({ "finally", "unchecked" })
	public Map<String,String> getCreditHistory(){
		Map<String,String> retMap	= null;
		InputStreamReader isr		= null;
		try{
			StringBuilder querySB	= new StringBuilder(Constants.remoteUrl);
			querySB.append("daikuanServlet?action=getCreditHistory");
			HttpResponse res		= commonGet(false, null, querySB.toString(), null, null, null);
			if(HttpStatus.SC_OK == res.getStatusLine().getStatusCode()){
				retMap			= new HashMap<String,String>();
				isr				= new InputStreamReader(res.getEntity().getContent(),"utf-8");
				String resString= new Source(isr).toString();
				if(resString.startsWith("{")){
					JSONObject obj		= JSONObject.fromObject(resString);
					Set<String> keys	= obj.keySet();
					for(String key : keys){
						String value	= obj.getString(key);
						retMap.put(key, value);
					}
				}
			}
		}catch(Exception e){
			Constants.log.error(className+" getCreditHistory",e);
		}finally{
			try {
				isr.close();
			} catch (IOException e) {
				Constants.log.error(className+" getCreditHistory isr",e);
			}
			return retMap;
		}
	}
	
	@SuppressWarnings({ "finally", "unchecked" })
	public Map<String,String> getLoanPurpose(){
		Map<String,String> retMap	= null;
		InputStreamReader isr		= null;
		try{
			StringBuilder querySB	= new StringBuilder(Constants.remoteUrl);
			querySB.append("daikuanServlet?action=getLoanPurpose");
			HttpResponse res		= commonGet(false, null, querySB.toString(), null, null, null);
			if(HttpStatus.SC_OK == res.getStatusLine().getStatusCode()){
				retMap			= new HashMap<String,String>();
				isr				= new InputStreamReader(res.getEntity().getContent(),"utf-8");
				String resString= new Source(isr).toString();
				if(resString.startsWith("{")){
					JSONObject obj		= JSONObject.fromObject(resString);
					Set<String> keys	= obj.keySet();
					for(String key : keys){
						String value	= obj.getString(key);
						retMap.put(key, value);
					}
				}
			}
		}catch(Exception e){
			Constants.log.error(className+" getLoanPurpose",e);
		}finally{
			try {
				isr.close();
			} catch (IOException e) {
				Constants.log.error(className+" getLoanPurpose isr",e);
			}
			return retMap;
		}
	}
	
	@SuppressWarnings({ "finally", "unchecked" })
	public Map<String,String> getProfession(){
		Map<String,String> retMap	= null;
		InputStreamReader isr		= null;
		try{
			StringBuilder querySB	= new StringBuilder(Constants.remoteUrl);
			querySB.append("daikuanServlet?action=getProfession");
			HttpResponse res		= commonGet(false, null, querySB.toString(), null, null, null);
			if(HttpStatus.SC_OK == res.getStatusLine().getStatusCode()){
				retMap			= new HashMap<String,String>();
				isr				= new InputStreamReader(res.getEntity().getContent(),"utf-8");
				String resString= new Source(isr).toString();
				if(resString.startsWith("{")){
					JSONObject obj		= JSONObject.fromObject(resString);
					Set<String> keys	= obj.keySet();
					for(String key : keys){
						String value	= obj.getString(key);
						retMap.put(key, value);
					}
				}
			}
		}catch(Exception e){
			Constants.log.error(className+" getProfession",e);
		}finally{
			try {
				isr.close();
			} catch (IOException e) {
				Constants.log.error(className+" getProfession isr",e);
			}
			return retMap;
		}
	}
	
	@SuppressWarnings({ "finally", "unchecked" })
	public Map<String,String> getSecuredCar(){
		Map<String,String> retMap	= null;
		InputStreamReader isr		= null;
		try{
			StringBuilder querySB	= new StringBuilder(Constants.remoteUrl);
			querySB.append("daikuanServlet?action=getSecuredCar");
			HttpResponse res		= commonGet(false, null, querySB.toString(), null, null, null);
			if(HttpStatus.SC_OK == res.getStatusLine().getStatusCode()){
				retMap			= new HashMap<String,String>();
				isr				= new InputStreamReader(res.getEntity().getContent(),"utf-8");
				String resString= new Source(isr).toString();
				if(resString.startsWith("{")){
					JSONObject obj		= JSONObject.fromObject(resString);
					Set<String> keys	= obj.keySet();
					for(String key : keys){
						String value	= obj.getString(key);
						retMap.put(key, value);
					}
				}
			}
		}catch(Exception e){
			Constants.log.error(className+" getSecuredCar",e);
		}finally{
			try {
				isr.close();
			} catch (IOException e) {
				Constants.log.error(className+" getSecuredCar isr",e);
			}
			return retMap;
		}
	}
	
	@SuppressWarnings({ "finally", "unchecked" })
	public Map<String,List<DaikuanCondition>> getConditions(){
		Map<String,List<DaikuanCondition>> retMap	= null;
		InputStreamReader isr						= null;
		try{
			StringBuilder querySB	= new StringBuilder(Constants.remoteUrl);
			querySB.append("daikuanServlet?action=getConditions");
			HttpResponse res		= commonGet(false, null, querySB.toString(), null, null, null);
			if(HttpStatus.SC_OK == res.getStatusLine().getStatusCode()){
				retMap			= new HashMap<String,List<DaikuanCondition>>();
				isr				= new InputStreamReader(res.getEntity().getContent(),"utf-8");
				String resString= new Source(isr).toString();
				if(resString.startsWith("{")){
					JSONObject obj		= JSONObject.fromObject(resString);
					Set<String> keys	= obj.keySet();
					for(String key : keys){
						JSONArray array	= obj.getJSONArray(key);
						if(null != array && array.size() > 0){
							for(int i=0;i<array.size();i++){
								JSONObject tmpObj	= array.getJSONObject(i);
								if(null != tmpObj){
									String id		= tmpObj.getString("id");
									String name		= tmpObj.getString("name");
									String parentID	= tmpObj.getString("parentID");
									String parentName	= tmpObj.getString("parentName");
									
									DaikuanCondition dc	= new DaikuanCondition();
									dc.setId(id);
									dc.setName(name);
									dc.setParentID(parentID);
									dc.setParentName(parentName);
									
									List<DaikuanCondition> list	= retMap.get(parentID);
									if(null == list){
										list = new ArrayList<DaikuanCondition>();
										retMap.put(parentID, list);
									}
									list.add(dc);
								}
							}
						}
					}
				}
			}
		}catch(Exception e){
			Constants.log.error(className+" getConditions",e);
		}finally{
			try {
				isr.close();
			} catch (IOException e) {
				Constants.log.error(className+" getConditions isr",e);
			}
			return retMap;
		}
	}
	
	@SuppressWarnings({ "finally", "unchecked" })
	public Map<String,List<City>> getCities(){
		Map<String,List<City>> retMap	= null;
		InputStreamReader isr			= null;
		try{
			StringBuilder querySB	= new StringBuilder(Constants.remoteUrl);
			querySB.append("daikuanServlet?action=getCities");
			HttpResponse res		= commonGet(false, null, querySB.toString(), null, null, null);
			if(HttpStatus.SC_OK == res.getStatusLine().getStatusCode()){
				retMap			= new HashMap<String,List<City>>();
				isr				= new InputStreamReader(res.getEntity().getContent(),"utf-8");
				String resString= new Source(isr).toString();
				if(resString.startsWith("{")){
					JSONObject obj		= JSONObject.fromObject(resString);
					Set<String> keys	= obj.keySet();
					for(String key : keys){
						JSONArray tmpArray	= obj.getJSONArray(key);
						if(null != tmpArray){
							for(int i=0;i<tmpArray.size();i++){
								JSONObject tmpObj	= tmpArray.getJSONObject(i);
								
								String cityName = tmpObj.getString("cityName");
								String id 		= tmpObj.getString("id");
								String pid		= tmpObj.getString("pid");
								String province = tmpObj.getString("province");
								
								City city		= new City();
								city.setCityName(cityName);
								city.setId(id);
								city.setPid(pid);
								city.setProvince(province);
								
								List<City> cities	= retMap.get(province);
								if(null == cities){
									cities			= new ArrayList<City>();
									retMap.put(province, cities);
								}
								cities.add(city);
							}
						}
					}
				}
			}
		}catch(Exception e){
			Constants.log.error(className+" getCities",e);
		}finally{
			try {
				isr.close();
			} catch (IOException e) {
				Constants.log.error(className+" getCities isr",e);
			}
			return retMap;
		}
	}
	
	public static void main(String[] args){
		ReadDaikuanService service	= new ReadDaikuanService();
		/*
		List<Daikuan> list			= service.getDaikuanList(null, null, null, "1", null, null);
		for(int i=0;i<list.size();i++){
			System.out.println(list.get(i).getOrganization()+"~"+list.get(i).getName());
		}
		*/
		System.out.println(service.getCities());
	}
}